package com.demo.webflux.datar2bdc;

import java.time.Duration;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.r2dbc.core.DatabaseClient;
import org.springframework.data.r2dbc.core.DefaultReactiveDataAccessStrategy;
import org.springframework.data.r2dbc.dialect.MySqlDialect;
import org.springframework.data.r2dbc.repository.support.R2dbcRepositoryFactory;
import org.springframework.data.relational.core.mapping.RelationalMappingContext;

import com.demo.webflux.Constant;
import com.demo.webflux.PropertiesInnerUtil;

import dev.miku.r2dbc.mysql.MySqlConnectionConfiguration;
import dev.miku.r2dbc.mysql.MySqlConnectionFactory;
import io.r2dbc.spi.ConnectionFactory;

@SpringBootApplication
public class App {

	//启动后发现应用运行于Netty上:
	//Netty started on port(s): 8083
	public static void main(String[] args) {
		SpringApplication.run(App.class, args);
	}

	private static String userName = PropertiesInnerUtil.getString(Constant.DATASOURCE_LOCATION, "datasource.username");
	private static String password = PropertiesInnerUtil.getString(Constant.DATASOURCE_LOCATION, "datasource.password");

	@Bean
    public ConnectionFactory connectionFactory() {
		MySqlConnectionConfiguration.Builder builder = MySqlConnectionConfiguration.builder()
	            .host("10.16.9.34")
	            .port(3306)
	            .connectTimeout(Duration.ofSeconds(3))
	            .username(userName)
	            .password(password)
	            .database("sms_crm_db");

		MySqlConnectionConfiguration configuration = builder.build();
		return MySqlConnectionFactory.from(configuration);
    }

	@Bean
    public DatabaseClient databaseClient(ConnectionFactory connectionFactory) {
        return DatabaseClient.builder().connectionFactory(connectionFactory).build();
    }

	@Bean
	public BookRepository bookRepository(DatabaseClient client) {
		RelationalMappingContext cnt = new RelationalMappingContext(); // 将行映射到实体，在现在好像不需要这个
		return new R2dbcRepositoryFactory(client, new DefaultReactiveDataAccessStrategy(new MySqlDialect())).getRepository(BookRepository.class);
	}

}
